<template>
	<jk-dialog
		v-model="showDialog"
		title="批量设置点位"
		width="1200px"
		:show-content-loading="showLoading"
		:confirm-btn-loading="saveBtnLoading"
		append-to-body
		@on-cancel="onVisibleChange(false)"
		@on-visible-change="onVisibleChange"
		@on-confirm="onConfirmBtn"
	>
		<div ref="box1">
			<div class="margin-bottom-4 flex-start-center" style="align-items: flex-end;font-size: 12px;">
				<jk-button size="mini" type="primary" icon="el-icon-plus" @click="selectMachineDialogState = true">机台列表</jk-button>
				<span>({{ machineList.length }}台)</span>
			</div>
			<div class="machine-list-box">
				<div class="machine-list-box-inner">
					<div
						v-for="(item, index) in machineList || []"
						:key="index"
						:style="{width: `calc(100% / 12)`, padding: '2px 2px'}"
						style="box-sizing: border-box;margin-right: 0;"
					>
						<el-tag
							class="width-100-percent flex-between-center"
							size="medium"
							closable
							:type="selectItem.id === item.id ? 'success' : 'primary'"
							@close="machineList.splice(index, 1)"
							@click="selectItem = item"
						>{{ item.name }}</el-tag>
					</div>
				</div>
			</div>
		</div>
		<div ref="box3" class="flex-between-center margin-bottom-4">
			<div class="flex-start-center" style="align-items: flex-end;font-size: 12px;">
				<jk-button :disabled="!Object.keys(selectItem).length" size="mini" type="primary" icon="el-icon-plus" @click="onAddMonitorParamBtn">添加点位</jk-button>
				<span>(选中以上任意机台来获取点位选项)</span>
			</div>
			<div class="flex-start-center">
				<jk-button size="mini" type="primary" class="item-gap" icon="el-icon-document-copy" plain @click="onCopyBtn">复制</jk-button>
				<jk-button size="mini" type="primary" icon="el-icon-document-checked" plain @click="onPasteBtn">粘贴</jk-button>
			</div>
		</div>
		<jk-table ref="jkTable" border :data="tableData" :height="dialogTableHeight - 30">
			<vxe-column width="60" align="center">
				<template #default>
					<div class="drag-btn"><i class="el-icon-rank"></i></div>
				</template>
				<template #header>
					<el-popover title="提示" content="双击拖动调整顺序！" placement="bottom" trigger="hover">
						<i slot="reference" class="el-icon-info drag-info-icon"></i>
					</el-popover>
				</template>
			</vxe-column>
			<vxe-column title="操作" align="center" field="operation" :width="70">
				<template slot-scope="scope">
					<div class="flex-center">
						<el-button size="mini" icon="el-icon-minus" @click="onRemoveTemHumBtn(scope)"></el-button>
					</div>
				</template>
			</vxe-column>
			<vxe-column title="序号" align="center" type="seq" :width="50"></vxe-column>
			<vxe-column title="点位" field="signalName" :min-width="100"></vxe-column>
			<vxe-column title="别名" align="left" field="typeName" :min-width="100">
				<template slot-scope="scope">
					<jk-input v-model="scope.row.typeName" placeholder="" size="mini"></jk-input>
				</template>
			</vxe-column>
			<vxe-column title="纺纱方式" align="left" field="spinTypeId" :min-width="180">
				<template slot-scope="scope">
					<jk-select v-model="scope.row.spinTypeId" :option-list="spinTypeList" placeholder="" size="mini"></jk-select>
				</template>
			</vxe-column>
			<vxe-column title="单位朝向" align="center" field="unitLocal" :width="110">
				<template slot-scope="scope">
					<el-radio-group v-model="scope.row.unitLocal" size="mini">
						<el-radio-button :label="true">左</el-radio-button>
						<el-radio-button :label="false">右</el-radio-button>
					</el-radio-group>
				</template>
			</vxe-column>
			<vxe-column title="下限值" align="left" field="minValue" :width="100">
				<template slot-scope="scope">
					<jk-input v-model="scope.row.minValue" placeholder="" size="mini"></jk-input>
				</template>
			</vxe-column>
			<vxe-column title="标准值" align="left" field="value" :width="100">
				<template slot-scope="scope">
					<jk-input v-model="scope.row.value" placeholder="" size="mini"></jk-input>
				</template>
			</vxe-column>
			<vxe-column title="上限值" align="left" field="maxValue" :width="100">
				<template slot-scope="scope">
					<jk-input v-model="scope.row.maxValue" placeholder="" size="mini"></jk-input>
				</template>
			</vxe-column>
			<!--<vxe-column title="误差范围" align="left" field="errorRange" :width="100">
                <template slot-scope="scope">
                    <jk-input v-model="scope.row.errorRange" placeholder="" size="mini"></jk-input>
                </template>
            </vxe-column>-->
			<vxe-column title="是否监控" align="center" field="ifMonitoring" :width="70">
				<template slot-scope="scope">
					<el-switch v-model="scope.row.ifMonitoring"></el-switch>
				</template>
			</vxe-column>
			<vxe-column title="是否显示" align="center" field="ifShow" :width="70">
				<template slot-scope="scope">
					<el-switch v-model="scope.row.ifShow"></el-switch>
				</template>
			</vxe-column>
		</jk-table>
		<checkboxSignalDialog
			:machine-code="selectItem.code"
			:default-select-rows="tableData || []"
			:dialog-state="checkboxSignalDialogState"
			@on-visible-change="onVisibleChangeOfCheckboxSignalDialog"
			@on-confirm="onConfirmOfCheckboxSignalDialog"
		></checkboxSignalDialog>
		<checkbox-machine-dialog
			:checked-data="machineList"
			check-key-name="id"
			:dialog-state="selectMachineDialogState"
			@on-visible-change="onVisibleChangeOfSelectMachineDialog"
			@on-confirm="onConfirmBtnOfSelectMachineDialog"
		></checkbox-machine-dialog>
	</jk-dialog>
</template>

<script>
    import calHeight from '/src/mixins/cal-dialog-height';
    import {
        productionIotMachineGetAllSingle, machineManagerMachineUpdateBatchMonitoringParams
    } from '../../../../api/machine/machineArchives';
    import { systemBusinessDictPage } from '../../../../api/basicData/businessDict';
    import Sortable from 'sortablejs';
    import checkboxSignalDialog from './checkbox-signal.dialog';
    import checkboxMachineDialog from '../../qingHuaLine/components/checkbox-machine-dialog';
    export default {
        name: 'BatchSetSignalDialog',
        components: {
            checkboxMachineDialog,
            checkboxSignalDialog
        },
        props: {
            dialogState: {
                type: Boolean,
                default: false
            },
            dataId: {
                type: [String, Number],
                default: ''
            }
        },
        mixins: [calHeight],
        data() {
            return {
                selectMachineDialogState: false,
                selectItem: {},
                tableData: [],
                spinTypeList: [],
                checkboxSignalDialogState: false,
                machineList: [],
                saveBtnLoading: false,
                showDialog: false,
                showLoading: true,
                confirmBtnLoading: false,
                saveDialogState: false
            };
        },
        methods: {
            onVisibleChangeOfSelectMachineDialog(e) {
                this.selectMachineDialogState = e;
            },
            onConfirmBtnOfSelectMachineDialog(arr) {
                if (arr.length) {
                    this.selectMachineDialogState = false;
                    const list = this.machineList ? JSON.parse(JSON.stringify(this.machineList)) : [];
                    arr.forEach(x => {
                        list.push({
                            id: x.id,
                            code: x.code,
                            name: x.name,
                            processId: x.processId,
                            processCode: x.processCode,
                            processName: x.processName,
                            sortNum: x.sortNum
                        });
                    });
                    list.sort((a, b) => {
                        return a.sortNum - b.sortNum;
                    });
                    if (!Object.keys(this.selectItem).length && list.length) {
                        this.selectItem = list[0];
                    }
                    this.machineList = list;
                }
            },
            onRemoveTemHumBtn(scope) {
                this.tableData.splice(scope.rowIndex, 1);
            },
            onConfirmOfCheckboxSignalDialog(arr) {
                arr.forEach(item => {
                    this.tableData.push({
                        typeId: item.typeId,
                        signalId: item.id,
                        signalCode: item.code,
                        signalName: item.name,
                        typeName: item.name, // 注：typeName: 已被用作signalName的别名
                        errorRange: null,
                        maxValue: null,
                        minValue: null,
                        ifMonitoring: true,
                        ifShow: true,
                        value: null,
                        unitLocal: true
                    });
                });
                this.checkboxSignalDialogState = false;
            },
            onVisibleChangeOfCheckboxSignalDialog(e) {
                this.checkboxSignalDialogState = e;
            },
            loadSortTable() {
                this.$nextTick(() => {
                    const xTable = this.$refs.jkTable.$refs.xTable;
                    this.sortable1 = Sortable.create(xTable.$el.querySelector('.body--wrapper>.vxe-table--body tbody'), {
                        handle: '.drag-btn',
                        animation: 500,
                        onEnd: ({ newIndex, oldIndex }) => {
                            const currRow = this.tableData.splice(oldIndex, 1)[0];
                            this.tableData.splice(newIndex, 0, currRow);
                        }
                    });
                });
            },
            onCodeChange() {
                this.getMonitorTypeListRequest();
            },
            onCopyBtn() {
                localStorage.setItem('signalList', JSON.stringify(this.tableData));
            },
            onPasteBtn() {
                const arr = localStorage.getItem('signalList') ? JSON.parse(localStorage.getItem('signalList')) : [];
                arr.forEach(x => {
                    delete x.id;
                });
                this.tableData = arr;
            },
            onAddMonitorParamBtn() {
                this.checkboxSignalDialogState = true;
            },
            getParamData() {
                const params = {};
                params.machineCodeList = this.machineList.map(x => x.code);
                params.monitoringParams = this.tableData;

                let spinTypeItem = {};
                params.monitoringParams = params.monitoringParams ? params.monitoringParams.map((x, index) => {
                    x.sortNum = index + 1;
                    spinTypeItem = this.spinTypeList.find(k => k.id === x.spinTypeId) || {};
                    x.spinTypeCode = spinTypeItem.code;
                    x.spinTypeName = spinTypeItem.name;
                    return x;
                }) : [];
                return params;
            },
            onConfirmBtn() {
                if (this.machineList && this.machineList.length) {
                    this.createAndUpdateRequest();
                } else {
                    this.$tipsBar(this, 'custom', 'warning', '机台不能为空!');
                }
            },
            createAndUpdateRequest() {
                this.saveBtnLoading = true;
                machineManagerMachineUpdateBatchMonitoringParams(this.getParamData()).then(res => {
                    this.saveBtnLoading = false;
                    if (res.data.status === 200) {
                        this.$tipsBar(this, 'save');
                        this.$emit('on-finish');
                    }
                });
            },
            onVisibleChange(e) {
                this.$emit('on-visible-change', e);
                if (!e) {
                    Object.assign(this.$data, this.$options.data());
                }
            },
            getSpinTypeListRequest() {
                return systemBusinessDictPage({ categoryCode: 'SPIN_TYPE' }).then(res => {
                    if (res.data.status === 200) {
                        this.spinTypeList = res.data.res || [];
                    }
                });
            },
            getMonitorTypeListRequest() {
                this.typeList = [];
                if (!this.selectItem.code) return;
                return productionIotMachineGetAllSingle({
                    number: this.selectItem.code
                }).then(res => {
                    if (res.data.status === 200) {
                        this.typeList = res.data.res ? res.data.res.map(x => {
                            return x;
                        }) : [];
                    }
                });
            },
            async getDependentData() {
                this.showLoading = true;
                await this.getSpinTypeListRequest();
                await this.getMonitorTypeListRequest();
                this.showLoading = false;
            }
        },
        watch: {
            dialogState(newVal) {
                this.showDialog = newVal;
                if (newVal) {
                    this.loadSortTable();
                    this.getDependentData();
                }
            }
        }
    };
</script>
<style scoped lang="scss">
.machine-list-box {
    height: 200px;
    padding: 4px;
    border: solid 1px #eee;
    border-radius: 4px;
    margin-bottom: 10px;
    .machine-list-box-inner {
        height: 100%;
        display: flex;
        flex-wrap: wrap;
        overflow: auto;
        box-sizing: border-box;
        align-content: flex-start;
    }
}
.drag-info-icon {
    font-size: 14px;
}
.drag-btn {
    cursor: move;
    color: #2d8cf0;
    transition: all .5s;
    font-size: 18px;
}
</style>
